package cn.madis.ymcc.smsconsoumer;
import cn.madis.exception.GlobalException;
import cn.madis.ymcc.domain.MessageSms;

import cn.madis.ymcc.dto.EmailSend2MQ;
import cn.madis.ymcc.service.IMessageSmsService;
import cn.madis.ymcc.util.SmsUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(
        consumerGroup = "service-common-consumer",//组名
        topic = "topic-user",
        selectorExpression = "tags-phone",//tags
        messageModel = MessageModel.CLUSTERING//集群模式一个消费者只能给到一个消费者

)
public class CourserConsumer implements RocketMQListener<MessageExt>{
    @Autowired
    private IMessageSmsService messageSmsService;
    @Override
    public void onMessage(MessageExt messageExt) {

        try {
            byte[] body = messageExt.getBody();
            String s = new String(body, CharsetUtil.UTF_8);
            EmailSend2MQ emailSend2MQ = JSONObject.parseObject(s, EmailSend2MQ.class);
            for (MessageSms messageSms : emailSend2MQ.getList()) {
                String phone = messageSms.getPhone();
                String content = messageSms.getContent();
                //2.调用短信网关发送
                SmsUtils.sendMsg(phone,content);

                //1.保持发送记录到数据库
                messageSmsService.insert(messageSms);
            }



        } catch (RuntimeException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("邮件发送失败");
        }
    }



    }

